﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using WeChat.Common;
using BLL;
using WeChat.Common2;
using System.Collections.Generic;
using System.Drawing;
using System.Web.SessionState;
using WxPayAPI;

namespace WeChat.JsSDK.WxPay
{
    public partial class WechatPay : System.Web.UI.Page, IRequiresSessionState
    {
        /// <summary>
        /// 调用js获取收货地址时需要传入的参数
        /// 格式：json串
        /// 包含以下字段：
        ///     appid：公众号id
        ///     scope: 填写“jsapi_address”，获得编辑地址权限
        ///     signType:签名方式，目前仅支持SHA1
        ///     addrSign: 签名，由appid、url、timestamp、noncestr、accesstoken参与签名
        ///     timeStamp：时间戳
        ///     nonceStr: 随机字符串
        /// </summary>
        public static string wxEditAddrParam { get; set; }
        //项目地址
        string srcUrl = ConfigurationManager.AppSettings["srcUrl"];
        //操作员
        string business_no = ConfigurationManager.AppSettings["business_no"];
        //收款员
        string tn = ConfigurationManager.AppSettings["tn"];
        string user = ConfigurationManager.AppSettings["user"];
        //密码
        string pwd = ConfigurationManager.AppSettings["pwd"];
        //机器码
        string sn = ConfigurationManager.AppSettings["sn"];
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {

                string userAgent = Request.UserAgent;
                if (userAgent.ToLower().Contains("micromessenger"))
                {
                    Log.Info(this.GetType().ToString(), "page load");
                    JsApiPay jsApiPay = new JsApiPay(this);
                    try
                    {
                        //调用【网页授权获取用户信息】接口获取用户的openid和access_token
                        jsApiPay.GetOpenidAndAccessToken();

                        //获取收货地址js函数入口参数
                        wxEditAddrParam = jsApiPay.GetEditAddressParameters();
                        ApplicationLog.Write("微信充值openid:" + jsApiPay.openid);
                        ViewState["openid"] = jsApiPay.openid;
                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.Write("微信充值异常信息=" + ex.Message);
                        Response.Write("<span style='color:#FF0000;font-size:20px'>" + "页面加载出错，请重试" + "</span>");
                        btn1.Visible = false;
                    }
                }



                //认证后得到code值
                if (Request.QueryString["code"] != null || Request.QueryString["code"] != "")
                {
                    string code = Request.QueryString["code"];
                    if (Session["openid"] == null || Session["openid"].ToString() == "")
                    {
                        Session["openid"] = OAuthHelper.getOpenid(code);
                    }
                    string openid = Session["openid"].ToString();
                    ApplicationLog.Write("获取到的openid:" + openid);
                    //验证是否绑定账号,未绑定则跳转提示绑定账号
                    if (new BindIdBLL().verifyId(openid))
                    {


                        GetUserInfoBLL gb1 = new GetUserInfoBLL();
                        DataTable dt1 = gb1.getUserInfos(openid).Tables[0];
                        string rfzt = dt1.Rows[0]["rfzt"].ToString();




                        ApplicationLog.Write("获取到的rfzt:" + rfzt);
                        if ("32" == rfzt)
                        {
                            // 
                            ApplicationLog.Write("获取到的rfzt:" + new GetUserInfoBLL().getUserInfos(openid));


                            try
                            {
                                GetUserInfoBLL gb = new GetUserInfoBLL();
                                DataSet ds = gb.getCZZSInfo(openid);
                                DataTable dt = ds.Tables[0];





                                //string a = dt.Rows[0]["zsje1"].ToString();//赠送金额1                                                        
                                //zsje1.Text = float.Parse(a).ToString();

                                //string b = dt.Rows[0]["zsje2"].ToString();//赠送金额2                                                       
                                //zsje2.Text = float.Parse(b).ToString();

                                //string c = dt.Rows[0]["zsje3"].ToString();//赠送金额3                                                       
                                //zsje3.Text = float.Parse(c).ToString();
                                //string d = dt.Rows[0]["zsje4"].ToString();//赠送金额4                                                        
                                //zsje4.Text = float.Parse(d).ToString();
                                //string f = dt.Rows[0]["zsje5"].ToString();//赠送金额5                                                        
                                //zsje5.Text = float.Parse(f).ToString();


                            }
                            catch (Exception ex)
                            {
                                Response.Write("<span style='color:#FF0000;font-size:20px'>" + "报错了" + ex.Message + "</span>");
                            }


                        }

                        else
                        {
                            Response.Write("非正常卡片，请检查卡状态！");

                            btn1.Enabled = false;
                        }


                    }

                    else
                    {
                        Response.Redirect("/Binding.aspx?openid=" + openid);
                    }



                }
            }

        }
        //密钥
        string publickey = "";
        //操作员
        string num = "";
        //提交支付
        protected void btn1_Click(object sender, EventArgs e)
        {
            string q = Request["bmmc"].ToString();
            string userAgent = Request.UserAgent;
            Context.Response.Write("<script>alert('"+userAgent+"')</script>");
            Session["q"] = q;
            string price = (Convert.ToDouble(Request["selVal"].ToString()) * 100).ToString();
            Session["moneys"] = price;
            if (q == null || q == "")
            {
                Context.Response.Write("<script>alert('请选择支付方式！')</script>");
                return;
            }
            if (q == "2")
            {
                if (userAgent.ToLower().Contains("micromessenger"))
                //if (1==1)
                {
                    string total_fee = price;
                    if (ViewState["openid"] != null)
                    {
                        string openid = ViewState["openid"].ToString();
                        //string openid = "T1JP35REQOYWRLY2ZHX0YII";
                        Session["wxopenid"] = openid;
                        string url = srcUrl + "JsApiPayPage.aspx?openid=" + openid + "&total_fee=" + total_fee;
                        Response.Redirect(url);
                    }
                    else
                    {
                        Response.Write("<span style='color:#FF0000;font-size:20px'>" + "页面缺少参数，请返回重试" + "</span>");
                        btn1.Visible = false;
                    }
                }
                else
                {
                    Log.Info(this.GetType().ToString(), "page load");
                    H5Pay h5Pay = new H5Pay();
                    string scip = GetIP();//获取客户端真实IP
                    string Opid = Session["openid"].ToString();
                    string url = h5Pay.GetPayUrl(scip, Opid, price);//通过统一下单接口进行H5支付
                    Response.Redirect(url);
                }

            }
            else
            {

                Secretkey();
                Operator();
                string userID = num;
                //String publickey = publickey;
                //String q = (this.comboBox1.SelectedIndex + 1).ToString();
                //if (q == "0") { MessageBox.Show("请选择支付类型"); return; }
                //此处自行验证各值合法性
                //string urldz = "http://59.175.191.227:20009/RetCallback.aspx";

                string urldz = srcUrl + "RetCallback.aspx";
                string json = "{\"a\":\"payCode\",\"i\":\"" + userID + "\",\"j\":\"" + price + "\",\"q\":\"" + q + "\",\"tn\":\"" + tn + "\",\"t\":\"3\",\"z\":\"2\",\"notify_url\":\"" + urldz + "?Types=" + "Recharge" + "&opId=" + Session["openid"] + "&money= " + price + "&q=" + q + "&business_no=" + business_no + "&tn=" + tn + "\"}";
                string returnTxt = RsaDemo.Common.HttpPost("s=" + RsaDemo.Common.rsaEncode(publickey, json, business_no));
                IDictionary<string, object> rlt = RsaDemo.Common.JsonToDictionary(returnTxt);
                if (rlt["f"].ToString() == "2")
                {
                    IDictionary<string, object> d = (IDictionary<string, object>)rlt["d"];
                    this.textBox8.Text = d["qr"].ToString();
                    Session["IsValue"] = d["qr"].ToString();
                    Session["q"] = q;
                    Session["o"] = d["o"].ToString();
                    Session["business_no"] = business_no;
                    Session["tn"] = tn;
                    Session["q"] = q;
                    Session["moneys"] = price;
                    string o = Context.Session["o"].ToString();
                    string openid = Context.Session["openid"].ToString();
                    string ryid = ReBLL.SelectRyid(openid);
                    DateTime dateTimes = DateTime.Now;
                    ReBLL.OrderNum(o, Convert.ToDouble(price), ryid, dateTimes, 2);
                    Response.Redirect(d["qr"].ToString());
                }
                else
                {
                    Context.Response.Write("<script>alert('请选择支付类型！')</script>");
                }
            }
        }
        //获取密钥
        public void Secretkey()
        {
            //此处自行验证各值合法性
            string json = "{\"a\":\"getKey\",\"e\":\"" + business_no + "\",\"sn\":\"" + sn + "\"}";
            string returnTxt = RsaDemo.Common.HttpPost("json=" + json);
            IDictionary<string, object> rlt = RsaDemo.Common.JsonToDictionary(returnTxt);
            if (rlt["f"].ToString() == "1")
            {
                IDictionary<string, object> d = (IDictionary<string, object>)rlt["d"];
                //this.richTextBox1.Text = d["k"].ToString();
                publickey = d["k"].ToString();
                //this.textBox5.Text = "0001";
            }
            else
            {
                //MessageBox.Show(rlt["m"].ToString());
            }
        }
        //操作员
        public void Operator()
        {
            //此处自行验证各值合法性
            string json = "{\"a\":\"login\",\"ou\":\"" + user + "\",\"op\":\"" + pwd + "\",\"tn\":\"" + tn + "\"}";
            string returnTxt = RsaDemo.Common.HttpPost("s=" + RsaDemo.Common.rsaEncode(publickey, json, business_no));
            IDictionary<string, object> rlt = RsaDemo.Common.JsonToDictionary(returnTxt);
            if (rlt["f"].ToString() == "1")
            {
                IDictionary<string, object> d = (IDictionary<string, object>)rlt["d"];
                //this.textBox6.Text = d["i"].ToString();
                num = d["i"].ToString();
            }
            else
            {
                //MessageBox.Show(rlt["m"].ToString());

            }
        }
        //因H5支付要求商户在统一下单接口中上传用户真实ip地址“spbill_create_ip”，故需要调用以下方法。
        public string GetIP()
        {
            HttpRequest request = HttpContext.Current.Request;
            string result = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = request.UserHostAddress;
            }
            if (string.IsNullOrEmpty(result))
            {
                result = "0.0.0.0";
            }
            return result;
        }
    }
}
